package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.core.redis.RedisCache;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.serve.vo.ProductVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备Service业务层处理
 * 
 * @author BIG
 * @date 2025-06-08
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient ioTDAClient;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //先从iot查询到产品列表
        ListProductsRequest request = new ListProductsRequest();
        ListProductsResponse response = ioTDAClient.listProducts(request);
        if(response.getHttpStatusCode()!= 200){
            throw new BaseException("物联网接口，同步失败");
        }
        List<ProductSummary> products = response.getProducts();
        //把查询到的产品列表先转成json样式放入redis中
        String productsStr = JSONUtil.toJsonStr(products);
        redisCache.setCacheObject("iot:productAll",productsStr);
    }
    /**
     * 从redis获取所有产品
     * @return
     */

    @Override
    public List<ProductVo> allProduct() {
        //从redis当中获取产品列表数据，返回
        String cacheObject = redisCache.getCacheObject("iot:productAll");
        if(StringUtils.isEmpty(cacheObject)){
            throw new BaseException("redis中产品列表数据不存在");
        }
        List<ProductVo> list = JSONUtil.toList(cacheObject, ProductVo.class);
        return list;
    }

    /**
     * 注册设备
     * @param deviceDto
     */

    @Override
    public void register(DeviceDto deviceDto) {
        //1.检查设备是否重复
        LambdaQueryWrapper<Device> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq( deviceDto.getDeviceName()!= null && !deviceDto.getDeviceName().isEmpty(),Device::getDeviceName,deviceDto.getDeviceName());
        long count1 = this.count(wrapper1);
        if(count1>0){
            throw new BaseException("设备名称重复");
        }
        //2.检查设备标识是否重复
        LambdaQueryWrapper<Device> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(deviceDto.getNodeId()!= null && !deviceDto.getNodeId().isEmpty(),Device::getNodeId,deviceDto.getNodeId());
        long count2 = this.count(wrapper2);
        if(count2>0){
            throw new BaseException("设备标识重复");
        }
        //3.检查同一位置是否绑定了相同产品
        LambdaQueryWrapper<Device> wrapper3 = new LambdaQueryWrapper<>();
        wrapper3.eq(deviceDto.getBindingLocation()!= null,Device::getBindingLocation,deviceDto.getBindingLocation())
                .eq(deviceDto.getLocationType()!= null,Device::getLocationType,deviceDto.getLocationType())
                .eq(deviceDto.getProductKey()!= null && !deviceDto.getProductKey().isEmpty(),Device::getProductKey,deviceDto.getProductKey())
                .eq(deviceDto.getPhysicalLocationType()!= null,Device::getPhysicalLocationType,deviceDto.getPhysicalLocationType());
        long count3 = this.count(wrapper3);
        if(count3>0){
            throw new BaseException("当前位置已绑定了同一件产品");
        }
        //4.注册设备到iot上
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new  AddDevice();
        body.withNodeId(deviceDto.getNodeId());
        body.withDeviceName(deviceDto.getDeviceName());
        body.withProductId(deviceDto.getProductKey());

        request.withBody(body);
        AddDeviceResponse response = ioTDAClient.addDevice(request);
        if(response.getHttpStatusCode() != 201){
            throw new BaseException("物联网接口，注册失败");
        }
        //5.保存设备到本地数据库中
        Device device = new Device();
        BeanUtils.copyProperties(deviceDto,device);
        device.setIotId(response.getDeviceId());
        device.setSecret(response.getAuthInfo().getSecret());

        this.save(device);
    }

    /**
     * 查询设备详情
     * @param iotId
     */

    @Override
    public DeviceDetailVo selectDeviceByIodId(String iotId) {
        //首先，从数据库中查询到设备信息
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq( iotId != null && !iotId.isEmpty(),Device::getIotId,iotId);
        Device device = this.getOne(wrapper);

        DeviceDetailVo deviceDetailVo = new DeviceDetailVo();
        BeanUtils.copyProperties(device,deviceDetailVo);
        Date createTime = device.getCreateTime();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(createTime.toInstant(), ZoneId.systemDefault());
        deviceDetailVo.setCreateTime(localDateTime);
        //把id传给iot接口，查询设备的状态和激活时间
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);
        ShowDeviceResponse response = ioTDAClient.showDevice(request);
        String status = response.getStatus();
        String activeTime = response.getActiveTime();
        if(StringUtils.isNotEmpty(activeTime)){
            LocalDateTime time = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
            time = time.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceDetailVo.setActiveTime(time);
        }
        deviceDetailVo.setDeviceStatus(status);
        //把设备详情返回给前端
        return deviceDetailVo;
    }

    /**
     * 修改设备
     * @param deviceDto
     */

    @Override
    public void updateIotDevice(DeviceDto deviceDto) {
        //修改iot
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(deviceDto.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(deviceDto.getDeviceName());
        request.setBody(body);
        UpdateDeviceResponse response = ioTDAClient.updateDevice(request);
        if(response.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口，修改设备失败");
        }
        //修改数据库
        Device device = new Device();
        BeanUtils.copyProperties(deviceDto,device);
        this.updateById(device);
    }

    /**
     * 删除设备
     * @param iotId
     */

    @Override
    public void removeDevice(String iotId) {
        //删除iot设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        DeleteDeviceResponse response = ioTDAClient.deleteDevice(request);
        if(response.getHttpStatusCode() != 204){
            throw new BaseException("物联网接口，修改设备失败");
        }

        //删除数据库中设备
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(iotId != null && !iotId.isEmpty(),Device::getIotId,iotId);
        this.remove(wrapper);
    }

    /**
     * 查询设备上报数据
     * @param iotId
     */
    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        //从iot获取上传数据
        List<Map<String, Object>> list = new ArrayList<>();
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = ioTDAClient.showDeviceShadow(request);
        if(response.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口，查询设备上报数据失败");
        }
        List<DeviceShadowData> shadowList = response.getShadow();
        Object properties = shadowList.get(0).getReported().getProperties();
        String eventTime = shadowList.get(0).getReported().getEventTime();
        LocalDateTime time = LocalDateTimeUtil.parse(eventTime, "yyyyMMdd'T'HHmmss'Z'");
        LocalDateTime localDateTime = time.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        JSONObject jsonObject = JSONUtil.parseObj(properties);

        for (Map.Entry<String, Object> entry : jsonObject) {
            Map<String,Object> map = new HashMap<>();
            map.put("functionId",entry.getKey());
            map.put("value",entry.getValue());
            map.put("eventTime",localDateTime);
            list.add(map);
        }

        //封装数据到Map集合中返回
        return list;
    }

    @Override
    public List<ServiceCapability> queryProduct(String productKey) {
        //从iot中获取产品的详情
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        ShowProductResponse response = ioTDAClient.showProduct(request);
        if(response.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口，查询产品详情失败");
        }
        List<ServiceCapability> productCapabilities = response.getServiceCapabilities();
        return productCapabilities;
    }
}
